package models.games;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

import core.User;

public class SchiacciaTalpe extends Game {
	private static final int HEIGHT = 10, WIDTH = 10;
	private static final double LEVEL_MULTIPLY_FACTOR = 0.1;
	private static final int EMPTY = 0, CLICKABLE = 1, NOT_CLICKABLE = -1;

	private static final int MAX_GAME = 10;
	private int gameCount = 0;

	private final int[][] table = new int[HEIGHT][WIDTH];
	private Random random = new Random();

	public SchiacciaTalpe(User user) {
		super(user);
	}

	public void startGame() {
		Scanner sc = new Scanner(System.in);
		System.out.println("Schiaccia Talpe");
		System.out.println("TALPA DA SCHIACCIARE: 1");
		System.out.println("CELLA VUOTA: 0");
		System.out.println("TALPA DA NON SCHIACCIARE: -1");
		update();
		while (gameCount < MAX_GAME) {
			System.out.println("SITUAZIONE MATRICE");
			printGame();
			System.out.println("Quale cella cliccare?");
			System.out.print("Coordinata i: ");
			int inputI = sc.nextInt();
			System.out.println();
			System.out.print("Coordinata j: ");
			int inputJ = sc.nextInt();
			verify(inputI, inputJ);
			gameCount++;
			update();
		}
	}

	public void update() {
		for (int[] x : table) { // SVUOTA LA MATRICE
			Arrays.fill(x, EMPTY);
		}
		for (int i = 0; i < table.length; i++) {
			for (int j = 0; j < table[i].length; j++) {
				double randomNumber = random.nextDouble(); // genera un double
															// da 0.0(incluso) a
															// 1.0(escluso)
				if (randomNumber < getLevel() * LEVEL_MULTIPLY_FACTOR) { // riempi
					table[i][j] = (random.nextDouble() > 0.5) ? CLICKABLE
							: NOT_CLICKABLE;
				}
			}
		}
		if (howMany(EMPTY) == table.length) {
			update();
		}
	}

	public void printGame() {
		for (int i = 0; i < table.length; i++) {
			System.out.println(Arrays.toString(table[i]));
		}
	}

	// ridefinizione provvisoria getLevel per testing
	@Override
	public int getLevel() {
		return 2;
	}

	public enum Verifica {
		CORRETTO, ERRATO, VUOTO
	};

	public Verifica verify(int i, int j) {
		System.out.println("cliccato " + i + " " + j);
		int value = table[i][j];

		if (value == CLICKABLE) {
			System.out.println("CORRETTO");
			score = score + (level + 1) * 250;
			table[i][j] = NOT_CLICKABLE;
			return Verifica.CORRETTO;
		}
		if (value == NOT_CLICKABLE) {
			System.out.println("ERRATO");
			return Verifica.ERRATO;
		}
		System.out.println("VUOTO");
		return Verifica.VUOTO;
	}

	private int howMany(int type) {
		int howMany = 0;
		for (int i = 0; i < table.length; i++) {
			for (int j = 0; j < table[i].length; j++) {
				if (table[i][j] == type)
					howMany++;
			}
		}
		return howMany;
	}

	public int[][] getTable() {
		return table;
	}

	@Override
	public int getGameKey() {
		return 6;
	}

}
